package com.ydj.app.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ydj.app.entity.WebUser;
import com.ydj.app.protocol.http.stream.StreamChatReq;
import com.ydj.app.service.ChatService;
import com.ydj.app.service.CommonService;
import com.ydj.framework.annotation.AllowGuest;
import com.ydj.framework.exception.CommonException;
import com.ydj.framework.exception.VerifyTokenException;
import com.ydj.framework.utils.JsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/stream")
@Api(tags = "流式")
public class StreamChatController {
    @Resource
    private ChatService chatService;
    @Resource
    private CommonService commonService;

    @AllowGuest
    @ApiOperation(value = "对话流式")
    @RequestMapping(value = "/chat", method = {RequestMethod.GET})
    @ApiOperationSupport(order = 11)
    public SseEmitter chat(@ApiIgnore HttpServletRequest request,
                           HttpServletResponse response,
                           @RequestParam(required = false) Long chatId,
                           @RequestParam String content) throws VerifyTokenException, CommonException {
        String origin = request.getHeader("origin");
        response.setHeader("access-Control-Allow-Origin", StringUtils.isBlank(origin) ? "*" : origin);
        response.setHeader("access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("access-Control-Max-Age", "1800");
        response.setHeader("access-Control-Allow-Headers", "*");
        response.setHeader("access-Control-Allow-Credentials", "true");
        response.setHeader("XDomainRequestAllowed", "1");
        response.setContentType("text/event-stream");

        log.info("调用chat(), get参数:{}", request.getQueryString());

        WebUser webUser = commonService.getUserForStream(request);
        SseEmitter emitter = chatService.chat(chatId, content, webUser);

        return emitter;
    }

}